package org.rapan;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.rapan.EJB.ConsultantInt;
import org.rapan.exceptions.InvalidLoginException;
import org.rapan.jpa.Consultant;

import com.vaadin.ui.Alignment;
import com.vaadin.ui.LoginForm;
import com.vaadin.ui.LoginForm.LoginListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Window;
import com.vaadin.ui.LoginForm.LoginEvent;

@SuppressWarnings("serial")
public class LoginWin extends Window {

	public LoginWin() {
		super("PASoft Consult - Login");
		Panel p = new Panel();
		GridLayout grLayout = new GridLayout();
		p.addComponent(new LoginLogoLayout());
		LoginForm lf = new LoginForm();
		p.addComponent(lf);
		lf.setPasswordCaption("Password");
		lf.setUsernameCaption("Email");
		setSizeFull();
		p.setWidth("230px");

		lf.addListener(new LoginListener() {

			public void onLogin(LoginEvent event) {

				String email = event.getLoginParameter("username");
				String password = event.getLoginParameter("password");

				try {
					InitialContext context = new InitialContext();
					ConsultantInt conInt = (ConsultantInt) context
							.lookup("Consult/ConsultantBean/local");
					try {
						Consultant c = conInt.login(email, password);
						RapanApplication ap = (RapanApplication) getApplication();
						ap.Login(c);
					} catch (InvalidLoginException e) {
						Notification not = new Notification("Login Failed",
								Notification.TYPE_HUMANIZED_MESSAGE);
						not.setDelayMsec(100 * 20);
						showNotification(not);
					}

				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		grLayout.addComponent(p);
		grLayout.setComponentAlignment(p, Alignment.MIDDLE_CENTER);
		addComponent(grLayout);

	}

}
